package com.baozun.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baozun.model.TUser;
import com.baozun.util.CommonConst;
import com.baozun.util.StringUtil;
import com.baozun.util.Tools;

/**
 * 
 * @Title:
 * @Company:宝尊电子商务有限公司
 * @Author:万世极缘
 * @Since:2014-12-28
 * @Copyright:Copyright (c) 2014
 * @ModifyDate:2014-12-28
 * @Version:1.1.0
 */
public class LoginFilter implements Filter {
    private static String[] excludeFilter = new String[] {"ajax_login_submit", "login_submit", "login", "logout", "forget_password_submit","find_password","find_password_submit"};

    public void destroy() {
        // TODO Auto-generated method stub

    }

    /**
     * 对登录进行过滤
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String url = httpServletRequest.getRequestURI();
        url = url.substring(0, url.lastIndexOf(".do"));
        System.out.println();
        // 得到controller
        if (StringUtil.isContain(excludeFilter, url)) {
            filterChain.doFilter(request, response);
        } else {
            RequestDispatcher requestDeDispatcher = request.getRequestDispatcher("../login.jsp");
            TUser user = (TUser) httpServletRequest.getSession().getAttribute(CommonConst.SESSION_USER);
            if (Tools.isEmpty(user)) {
                requestDeDispatcher.forward(request, response);
                // System.out.println("用户没有登陆，不允许操作");

                httpServletResponse.setHeader("Cache-Control", "no-store");
                httpServletResponse.setDateHeader("Expires", 0);
                httpServletResponse.setHeader("Pragma", "no-cache");
            } else {
                filterChain.doFilter(request, response);
            }
        }
    }

    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

}
